//
//  YXYSelectionViewController.m
//  Topit
//
//  Created by dllo on 15/12/5.
//  Copyright © 2015年 YXY. All rights reserved.
//

#import "YXYSelectionViewController.h"
#import "YXYNetWorkTool.h"
#import "YXYSelectionModel.h"
#import "YXYSelectionImageModel.h"
#import "UIImageView+WebCache.h"
#import "UIView+UIViewSAAdditions.h"
#import "YXYSelectionImageCollectionViewCell.h"
#import "YXYSkipViewController.h"
#import "MJRefresh.h"
@interface YXYSelectionViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, copy) NSString *url;
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *dataSource;
@property (nonatomic, retain)NSMutableArray *itemArray;
@property (nonatomic, retain)NSArray *array;
@property (nonatomic, retain)UICollectionView *collectionView;

//图片放大
@property (nonatomic, retain) UIView *backGround;
@property (nonatomic, retain) UIImageView *picture;
/**
 *  网络刷新参数
 */
@property (nonatomic, assign) int number;
@property (nonatomic, retain) UILabel *refresh;
/**
 *  数据库
 */
@property (nonatomic, retain) NSMutableArray *mutableArray;
@property (nonatomic, assign) BOOL click;

@property (nonatomic, retain) NSNumber *num;
@property (nonatomic, assign) long sum;
@end
@implementation YXYSelectionViewController

-(void)dealloc {
    [_url release];
    [_dataSource release];
    [_itemArray release];
    [_array release];
    [_collectionView release];
    [_mutableArray release];
    [_tableView release];
    [super dealloc];
}
- (instancetype)initWithURL:(NSString *)url
{
    self = [super init];
    if (self) {
        self.url = url;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    /**
     *  数据库
     */
    [self BaseHandle];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backDidButton:)];
    self.dataSource = [NSMutableArray arrayWithCapacity:0];
    self.itemArray = [NSMutableArray arrayWithCapacity:0];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width / 3, self.view.frame.size.height / 5);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    [flowLayout setHeaderReferenceSize:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height * 0.65)];

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 65) collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[YXYSelectionImageCollectionViewCell class] forCellWithReuseIdentifier:@"YXYSelectionImageCollectionViewCellIdentifier"];
    [_collectionView registerClass:[HeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeadView"];
    [self.view addSubview:_collectionView];
    [flowLayout release];
    [_collectionView release];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载";
    hud.mode = MBProgressHUDModeIndeterminate;
    [YXYNetWorkTool getWithUrl:_url parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        YXYSelectionModel *selectionModel = [[YXYSelectionModel alloc] initWithDictionary:result[@"info"][@"sbj"]];
        self.num = result[@"info"][@"num"];
        [_dataSource addObject:selectionModel];
        [selectionModel release];
        for (NSDictionary *dic in result[@"item"]) {
            YXYSelectionImageModel *selectionImageModel = [[YXYSelectionImageModel alloc] initWithDictionary:dic];
            [_itemArray addObject:selectionImageModel];
            [selectionImageModel release];
        }
        [hud hide:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [_collectionView reloadData];
        });
    } fail:^(NSError *error) {
        [ProgressHUD showError:@"请检查网络"];
    }];
   
    [self getFootRefresh];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
    [self.view nightMode];
    self.navigationController.navigationBar.translucent = NO;
    [self BaseHandle];
    [self.collectionView nightMode];
    [_collectionView reloadData];
}
#pragma mark - 数据库
- (void)BaseHandle {
    DataBaseHandle *dataBaseHandle = [DataBaseHandle shareDataBase];
    [dataBaseHandle openDataBase];
    [dataBaseHandle createTable];
    self.mutableArray = [NSMutableArray array];
    self.mutableArray = [dataBaseHandle selectDataBase];
    if (self.mutableArray.count == 0) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"attention"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(attentionDidPress:)];
        _click = 0;
        [self.tableView reloadData];
    }else {
        for (NSDictionary *dic in self.mutableArray) {
            if ([[dic valueForKey:@"URL"]isEqualToString:_url]) {
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"unattention"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(attentionDidPress:)];
                _click = 1;
                break;
            }else{
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"attention"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(attentionDidPress:)];
                _click = 0;
            }
        }
        
        [self.tableView reloadData];
    }
    [dataBaseHandle closedDataBase];
}
#pragma mark - attentionDidPress
- (void)attentionDidPress:(UIBarButtonItem *)sender {
    DataBaseHandle *dataBaseHandle = [DataBaseHandle shareDataBase];
    YXYSelectionModel *selectionModel = [_dataSource lastObject];
    [dataBaseHandle openDataBase];
    [dataBaseHandle createTable];
    if (_click) {
        sender.image = [[UIImage imageNamed:@"attention"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [dataBaseHandle deleteDataBase:selectionModel.name];
        [ProgressHUD showSuccess:@"取消成功"];
        _click = !_click;
    }else if(!_click){
        sender.image = [[UIImage imageNamed:@"unattention"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [dataBaseHandle insertDatabase:selectionModel.name withUrl:_url];
        [ProgressHUD showSuccess:@"收藏成功"];
        _click = !_click;
    }
    [dataBaseHandle closedDataBase];
}

#pragma mark - 底部刷新
-(void)getFootRefresh {
    [self.collectionView addFooterWithCallback:^{
        self.number += 30;
        NSString *num = [NSString stringWithFormat:@"%d", _number];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:num, @"offset", nil];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"正在加载";
        hud.mode = MBProgressHUDModeIndeterminate;
        [YXYNetWorkTool getWithUrl:self.url parameter:dic httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
            if ([result[@"item"] isKindOfClass:[NSArray class]]) {
                for (NSDictionary *dic in result[@"item"]) {
                    YXYSelectionImageModel *selectionImageModel = [[YXYSelectionImageModel alloc] initWithDictionary:dic];
                    [_itemArray addObject:selectionImageModel];
                    [selectionImageModel release];
                }
                [hud hide:YES];
            }else {
                UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"亲爱的" message:@"已经到底er了" preferredStyle:UIAlertControllerStyleAlert];
                [alertView addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }]];
                [self presentViewController:alertView animated:YES completion:nil];
            }
            [hud hide:YES];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_collectionView reloadData];
                [_collectionView footerEndRefreshing];
            });
        } fail:^(NSError *error) {
            [hud hide:YES];
            [ProgressHUD showError:@"请检查网络"];
        }];
    }];
}



#pragma mark - collectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _itemArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YXYSelectionImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YXYSelectionImageCollectionViewCellIdentifier" forIndexPath:indexPath];
    YXYSelectionImageModel *selectionImageModel = _itemArray[indexPath.item];
    [cell.images sd_setImageWithURL:[NSURL URLWithString:selectionImageModel.icon[@"url"]]];
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableView = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        HeadView *headView = (HeadView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeadView" forIndexPath:indexPath];
        [headView setSelectionModel:[_dataSource lastObject]];
        reusableView = headView;
    }
    return reusableView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    YXYSelectionImageModel *selectionImageModel = _itemArray[indexPath.item];
    YXYSkipViewController *skipVC = [[YXYSkipViewController alloc] initWithURL:selectionImageModel.next];
    skipVC.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:skipVC animated:YES];
//    [skipVC release];
}

#pragma mark - back
- (void)backDidButton:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
